const resolveApp = require("./path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const TerserPlugin = require('terser-webpack-plugin')

const {merge} = require("webpack-merge");

const prodConfig = require("./webpack.prod");
const devConfig = require("./webpack.dev");

const commonConfig = {
  // entry: "./src/main.js",
  entry: {
    main: "./src/main.js",
    index: "./src/index.js",
    // main: { import: "./src/main.js", dependOn: ['lodash', 'dayjs'] },
    // main: { import: "./src/main.js", dependOn: 'shared' },
    // index: { import: "./src/index.js", dependOn: 'shared' },
    // lodash: 'lodash',
    // dayjs: 'dayjs'
    // shared: ['lodash', 'dayjs']
  },
  output: {
    filename: "[name].bundle.js",
    path: resolveApp("./build"),
    chunkFilename: '[name].chunk.js'
  },
  resolve: {
    extensions: [".js", ".json", ".wasm", ".mjs", ".vue", ".jsx"],
    alias: {
      "@": resolveApp("./src"),
      pages: resolveApp("./src/pages"),
    },
  },
  optimization: {
    // 对代码进行压缩
    minimizer: [
      new TerserPlugin({
        extractComments: false,
      }),
    ],
    // natura: 使用自然数（不推荐）
    // named: 使用包所在的目录作为name（在开发环境推荐）
    // deterministic: 生成id，针对相同的文件生成的id是不变的
    chunkIds: 'deterministic',
    splitChunks: {
      // async 异步
      // initial 同步
      // all 异步/同步
      chunks: 'all',
      // 最小尺寸: 如果拆分出的包大小最小为minSize
      minSize: 20000,
      // 将大于maxSize的包, 拆分成不小于minSize的包
      // maxSize: 20000,
      // minChunks表示引入的包,至少被导入了几次
      minChunks: 1,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          filename: '[id]_vendors.js',
          name: 'chunk-vendors.js',
          priority: -10
        },
        // bar: {
        //   test: /bar_/,
        //   filename: '[id]_bar.js'
        // }
        default: {
          minChunks: 2,
          filename: 'common_[id].js',
          priority: -20
        }
      }
    },
    // true/multiple
    // single
    // object: name
    runtimeChunk: {
      // name: 'runtime-lyc'
      name: function(entrypoint) {
        return `lyc-${entrypoint.name}`
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        use: "babel-loader",
      },
      {
        test: /\.vue$/i,
        use: "vue-loader",
      },
      {
        test: /\.css$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              importLoaders: 2,
            },
          },
          "postcss-loader",
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({ template: resolveApp("./index.html") }),
    new VueLoaderPlugin(),
  ],
}

module.exports = function(env) {
  const isProduction = env.production;
  process.env.NODE_ENV = isProduction ? 'production' : 'development';

  const config = isProduction ? prodConfig : devConfig;

  return merge(commonConfig, config);
};
